
#include "spi.h"
#include "hc32_ll_spi.h"
#include "hc32_common.h"
#include "hc32_ll.h"
#include "gpio.h"

/* SPI_SCK Port/Pin definition */
#define SPI_SCK_PORT                    (GPIO_PORT_B)
#define SPI_SCK_PIN                     (GPIO_PIN_13)
#define SPI_SCK_FUNC                    (GPIO_FUNC_43)

/* SPI_MOSI Port/Pin definition */
#define SPI_MOSI_PORT                   (GPIO_PORT_B)	
#define SPI_MOSI_PIN                    (GPIO_PIN_12)	
#define SPI_MOSI_FUNC                   (GPIO_FUNC_40)//	

/* SPI_MISO Port/Pin definition */
#define SPI_MISO_PORT                   (GPIO_PORT_B)			
#define SPI_MISO_PIN                    (GPIO_PIN_14)			
#define SPI_MISO_FUNC                   (GPIO_FUNC_41)		

/* SPI unit and clock definition */
#define SPI_UNIT                        (CM_SPI3)			
#define SPI_UNIT_CLOCK                  (FCG1_PERIPH_SPI3)		
#define SPI_MASTER_MODE


void spiInit(void)			
{
    stc_spi_init_t stcSpiInit;
		
    /* configuration structure initialization */
    MEM_ZERO_STRUCT(stcSpiInit);
		
    /* Configuration peripheral clock */
	FCG_Fcg1PeriphClockCmd(FCG1_PERIPH_SPI3, ENABLE);
													 
    /* Configuration SPI pin */
	
	GPIO_SetFunc(SPI_SCK_PORT, SPI_SCK_PIN, SPI_SCK_FUNC);
    //PORT_SetFunc(SPI_NSS_PORT, SPI_NSS_PIN, SPI_NSS_FUNC, Disable);
    GPIO_SetFunc(SPI_MOSI_PORT, SPI_MOSI_PIN, SPI_MOSI_FUNC);
    GPIO_SetFunc(SPI_MISO_PORT, SPI_MISO_PIN, SPI_MISO_FUNC);

	
    /* Configuration SPI structure */
	SPI_StructInit(&stcSpiInit);
	
    SPI_Init(SPI_UNIT, &stcSpiInit);
    SPI_Cmd(SPI_UNIT, ENABLE);
}
 
uint8_t spiRW(uint8_t sendata)
{
	uint8_t revievedata;
	SPI_TransReceive(SPI_UNIT, &sendata, &revievedata, 1, 1000);
	return revievedata;
}


void xn297lWriteReg(uint8_t reg, uint8_t wdata)
{
    CSN_L;
    spiRW(reg);
    spiRW(wdata);
    CSN_H;
}

uint8_t xn297lReadReg(uint8_t reg)
{
    CSN_L;
    spiRW(reg);
    reg = spiRW(0);
    CSN_H;
    return reg;
}

// 写的起始地址是 W_REGISTER
void xn297lWriteBuf(uint8_t reg, uint8_t *pBuf, uint8_t length)
{
    int i;
    CSN_L;
    spiRW(reg);
    for (i = 0; i < length; i++)
    {
        spiRW(pBuf[i]);
    }
    CSN_H;
}

// 读的起始地址比写的起始地址少 W_REGISTER
void xn297lReadBuf(uint8_t reg, uint8_t *pBuf, uint8_t length)
{
    int i;
    CSN_L;
    spiRW(reg);
    for (i = 0; i < length; i++)
    {
        pBuf[i] = spiRW(0);
    }
    CSN_H;
}














